package Main;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ImdbCache {

	protected static String fn() {
		SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
		StringBuilder todayString = new StringBuilder(
				dateFormatter.format(new Date()));

		return "imdbCache" + todayString.toString() + ".xml";
	}

	protected Hashtable<String, String> entries;

	public String Get(String title) {
		return entries.get(title);
	}

	public void Put(String title, String data) {
		entries.put(title, data);
	}

	public ImdbCache() {
		entries = new Hashtable<String, String>();
	}

	public Boolean save() {

		try {
			FileOutputStream os = new FileOutputStream(fn(), false);

			XStream xs = new XStream(new DomDriver("UTF-8"));
			xs.toXML(this, os);

			return true;
		} catch (FileNotFoundException e) {
			System.out.println("ERROR saving " + fn());
		}
		return false;
	}

	public static ImdbCache load() {
		ImdbCache c = new ImdbCache();

		try {
			XStream xs = new XStream(new DomDriver());
			FileInputStream is = new FileInputStream(fn());
			xs.fromXML(is, c);
			return c;
		} catch (FileNotFoundException e) {
			System.out.println("ERROR loading " + fn());
		}

		return null;
	}

}
